import os
import sys
import django

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day01.settings")
django.setup()

from app01 import models

# root, _ = models.Tree.objects.get_or_create(name='配置', parent=None)
# children, _ = models.Tree.objects.get_or_create(name='网络管理', parent=root)
# children1, _ = models.Tree.objects.get_or_create(name='IPV4', parent=children)
# children2, _ = models.Tree.objects.get_or_create(name='配置保存', parent=children1)
# children3, _ = models.Tree.objects.get_or_create(name='IPV6', parent=children)
# children4, _ = models.Tree.objects.get_or_create(name='配置保存', parent=children3)
# children5, _ = models.Tree.objects.get_or_create(name='配置', parent=children4)
# children6, _ = models.Tree.objects.get_or_create(name='网络管理', parent=children5)
paths = [['配置', '网络管理', 'IPV4', '配置保存', '配置'],
         ['配置', '网络管理', 'IPV6', '配置保存', '配置', '网络管理'],
         ['配置', '网络管理', 'IPV7', '配置保存', '配置', '网络管理'],
         ['事件', '基础智能', '移动侦测', '警戒线'],
         ['通道', '网络管理', 'IPV6', '配置保存'],
         ]

dirs = [
    ['配置', '网络管理', 'IPV4', '配置保存', '配置'],
]


class MpttTableOperate():
    '''带有树状关系的数据库表'''

    def __init__(self, tree):
        '''需要一个树模型数据库'''
        self.tree_model = tree

    def _is_exist(self, level, name):
        '''查询当前树深度上有没有其他节点：如果没有需要重新开个分支'''
        node_obj = self.tree_model.objects.filter(level=level, name=name).first()
        return node_obj

    def gen_mptt_table(self, paths: list[list]):
        '''
        生成目录树状表-更新表
        :param paths: [[1,2,3],[1,2,4]... ...]
        :return: return not anything
        '''
        # 先清除表：方便管理
        self.tree_model.objects.all().delete()
        for path in paths:
            parent_obj_tree = None
            for level, name in enumerate(path):
                # 查找当前深度有没有其他节点
                find_node = self._is_exist(level, name)
                # 如果没有找到，需要从当前深度向后重新开个分支
                if not find_node:
                    for _, name in enumerate(path[level:]):
                        node, created = self.tree_model.objects.get_or_create(name=name, parent=parent_obj_tree)
                        # 更新 root
                        parent_obj_tree = node
                # 如果当前深度找到了，那么更新下当前的父目录
                else:
                    parent_obj_tree = find_node
        # ===============================================================================================

    def gen_family_path(self):
        '''多分支、全路径，好像用不上'''
        tree_obj = self.tree_model.objects.filter(id=311).first()
        full_path_qs = tree_obj.get_family()
        full_path_tapd = [i.name for i in full_path_qs]
        return '-'.join(full_path_tapd)

    def gen_ancestors_path(self, id):
        '''获取唯一一条祖先路径'''
        tree_obj = self.tree_model.objects.filter(id=id).first()
        full_path_qs = tree_obj.get_ancestors()
        full_path_list = [i.name for i in full_path_qs]
        full_path_list.append(tree_obj.name)
        full_path = '-'.join(full_path_list)
        return full_path

    def delete_dir(self, id):
        '''删除目录'''
        self.tree_model.objects.filter(id=id).delete()

    def move_dir(self, id_ori, id_dst):
        '''拖动目录移动-待完成'''
        ori_obj = self.tree_model.objects.filter(id=id_ori).first()
        dst_obj = self.tree_model.objects.filter(id=id_dst).first()
        pass

    def add_dir(self, id_dst, dir_name):
        '''
        添加一个目录
        :param id_dst:      插入到哪个目录下
        :param dir_name:    插入的目录名称
        :return:
        '''
        dst_obj = self.tree_model.objects.filter(id=id_dst).first()
        new_obj = self.tree_model(name=dir_name)
        new_obj.insert_at(target=dst_obj, save=True)


'''
循环便利：
1. 如果父ID是null那么它就是根节点A
2. 取其当前的id开始查找谁的父ID是A
3. 如果找到了,那么就把他作为A的children
4. 取children的id,继续查找谁的父ID是children
5. 如果找不到了，那么就把它的children置为[]，否则继续查找，直到找不到

'''


def build_tree(categories, parent_id=None):
    nodes = []
    for category in categories:
        if category.parent_id == parent_id:
            children = build_tree(categories, category.id)
            node = {
                "label": category.name,
                'id': category.id,
                'pid': category.parent_id,
                "children": children if children else []
            }
            nodes.append(node)

    return nodes


def build_category_tree(categories, parent_id=None):
    nodes = []
    for category in categories:
        if category.parent_id == parent_id:  # 如果是None表示一棵树的根节点

            children = build_category_tree(categories, category.id)

            node = {
                "label": category.name,
                'id': category.id,
                'pid': category.parent_id,
                "children": children if children else []
            }
            nodes.append(node)
    return nodes


# tree_obj = MpttTableOperate(models.Tree)
# tree_obj.gen_mptt_table(paths)

# 生成JSON数据

qs = models.Tree.objects.all()
q_list = build_category_tree(qs)
print(q_list)
